package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class BaseDao {

	private Connection con;

	public BaseDao(Connection con) {
		this.con = con;
	}

	public static Connection getConnection() throws SQLException, NamingException {
		Context context = new InitialContext();
		DataSource ds = (DataSource) context.lookup("java:comp/env/jdbc/EmployeeDB");
		return ds.getConnection();
	}

	// public void close(Connection connection) throws SQLException {
	// connection.close();
	// }

	public <E> List<E> query(String sql, Mapper<E> mapper, Object... objects) {
		try {
			PreparedStatement ps = con.prepareStatement(sql);
			if (objects != null) {
				for (int i = 0; i < objects.length; i++) {
					ps.setObject(i + 1, objects[i]);
				}
			}
			ResultSet rs = ps.executeQuery();
			List<E> list = new ArrayList<E>();
			while (rs.next()) {
				E e = mapper.doMapper(rs);
				list.add(e);
			}
			if (list.size() > 0)
				return list;

		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		return null;

	}

	public int update(String sql, Object... objects) {
		try {
			PreparedStatement ps = con.prepareStatement(sql);
			if (objects != null) {
				for (int i = 0; i < objects.length; i++) {
					ps.setObject(i + 1, objects[i]);
				}
			}
			return ps.executeUpdate();

		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return 0;

	}

}
